<?php

namespace app\api\controller;

use app\admin\model\BrowsingHistory as BrowsingHistoryModel;
use app\admin\model\ClassAddress;
use app\admin\model\Club;
use app\admin\model\ClubDtl;
use app\admin\model\SearchShool;
use app\admin\model\TeacherArea;
use app\admin\model\TeacherCollection as TeacherCollectionModel;
use app\admin\model\TeacherCourseDisplay;
use app\admin\model\TeacherDetail;
use app\common\controller\Api;

/**
 * 浏览历史接口
 */
class BrowsingHistory extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    //浏览历史列表
    public function history_list(){
        $params = $this->request->param();
        if(!isset($params['page'])||!$params['page']){
            $params['page'] = 1;
        }
        if(!isset($params['page_size'])||!$params['page_size']){
            $params['page_size'] = 10;
        }

        // 验证用户登录
        $user = $this->auth->getUser();
        if(!isset($user['id'])||!$user['id']){
            $this->error('当前登录用户不存在');
        }

        // 查询当前用户的浏览历史列表
        $query = BrowsingHistoryModel::where(['user_id' => $user['id']])
            ->with(['teacherDetailS'])
            ->order('addtime', 'desc')
            ->order('id', 'desc')
            ->paginate($params['page_size']);

        $list = $query->getCollection();
        $arr = [];
        foreach ($list as $k => $v) {

            $arr[$k]['id'] = $v['id']; // 收藏记录id
            $arr[$k]['teacher_detail_id'] = $v['teacher_detail_id']; // 教师课程id
            $arr[$k]['addtime'] = $v['addtime']; // 收藏时间

            // 教师信息
            $arr[$k]['user_id'] = isset($v['teacher_detail_s']['identity']['user_id']) ? $v['teacher_detail_s']['identity']['user_id'] : '';
            $arr[$k]['name'] = isset($v['teacher_detail_s']['identity']['name']) ? $v['teacher_detail_s']['identity']['name'] : '';
            $arr[$k]['avatar'] = isset($v['teacher_detail_s']['identity']['user']['avatar']) ? $v['teacher_detail_s']['identity']['user']['avatar'] : '';

            // 课程信息
            $arr[$k]['club_name'] = isset($v['teacher_detail_s']['club_dtl_s']['name']) ? $v['teacher_detail_s']['club_dtl_s']['name'] : '';
            $arr[$k]['hourly_rate'] = isset($v['teacher_detail_s']['hourly_rate']) ? $v['teacher_detail_s']['hourly_rate'] : '';
            // 使用5分制格式化评分
            $score = isset($v['teacher_detail_s']['score']) ? $v['teacher_detail_s']['score'] : '';
            $arr[$k]['score'] = $this->formatScore($score);
            $arr[$k]['people'] = isset($v['teacher_detail_s']['people']) ? $v['teacher_detail_s']['people'] : '';
            $arr[$k]['is_premium'] = isset($v['teacher_detail_s']['is_premium']) ? $v['teacher_detail_s']['is_premium'] : '';
            $week = isset($v['teacher_detail_s']['identity']['appointment_time_week']) ? $v['teacher_detail_s']['identity']['appointment_time_week'] : '';
            $time = isset($v['teacher_detail_s']['identity']['appointment_time']) ? $v['teacher_detail_s']['identity']['appointment_time'] : '';
            $arr[$k]['appointment_time_week']    = $week.' '.$time;
            $arr[$k]['appointment_time']    = $time;
            $arr[$k]['appointment_week']    = $week;
            $area = isset($v['teacher_detail_s']['identity']['area']) ? explode(',',$v['teacher_detail_s']['identity']['area']) : [];
            $area_arr = TeacherArea::get_arr();
            $area_name = '';
            foreach ($area as $kk=>$vv){
                $area_name .= isset($area_arr[$vv]) ? $area_arr[$vv].',' : '';
            }
            $arr[$k]['area_name'] = trim($area_name,',');
            $arr[$k]['tag_me']    = $v['teacher_detail_s']['tag_me'];
            
            // 检查教师和课程是否隐藏
            // main_status: 1显示，2隐藏
            // detail_status: 1显示，2隐藏
            // 只有当两个都是1（显示）时，才为1（显示），任何一个为2（隐藏）就为2（隐藏）
            $main_status = isset($v['teacher_detail_s']['identity']['main_status']) ? (int)$v['teacher_detail_s']['identity']['main_status'] : 1;
            $detail_status = isset($v['teacher_detail_s']['detail_status']) ? (int)$v['teacher_detail_s']['detail_status'] : 1;
            
            // 两个同时不隐藏（都为1）才为1，任何一个为2就为2
            if ($main_status == 1 && $detail_status == 1) {
                $arr[$k]['status'] = 1; // 显示
            } else {
                $arr[$k]['status'] = 2; // 隐藏
            }
            
            // 检查是否收藏：1已收藏，2未收藏
            $is_collected = 2; // 默认2=未收藏
            if (isset($v['teacher_detail_id'])) {
                $collection = TeacherCollectionModel::where(['user_id' => $user['id'], 'teacher_detail_id' => $v['teacher_detail_id']])->find();
                if ($collection) {
                    $is_collected = 1;
                }
            }
            $arr[$k]['is_collected'] = $is_collected; // 1已收藏，2未收藏
        }

        $data = [
            'list' => $arr,
            'count' => $query->total()
        ];

        $this->success('浏览历史列表', $data);
    }


    //删除浏览历史
    public function del_history(){
        $params = $this->request->param();

        // 验证用户登录
        $user = $this->auth->getUser();
        if(!isset($user['id'])||!$user['id']){
            $this->error('当前登录用户不存在');
        }

        // 验证参数：必须传id
        if(!isset($params['id']) || !$params['id']){
            $this->error('请传入浏览历史记录id');
        }

        // 处理id参数：可能是字符串（逗号分隔）或数组
        $ids = [];
        if(is_array($params['id'])){
            $ids = $params['id'];
        }else{
            // 字符串格式，按逗号分隔
            $ids = explode(',', $params['id']);
        }

        // 过滤空值和转换为整数
        $ids = array_filter(array_map('intval', $ids));
        if(empty($ids)){
            $this->error('无效的浏览历史记录id');
        }

        // 查询浏览历史记录（只能删除自己的记录）
        $histories = BrowsingHistoryModel::where('user_id', $user['id'])
            ->where('id', 'in', $ids)
            ->select();

        if(!$histories){
            $this->error('浏览历史记录不存在或无权删除');
        }

        // 删除浏览历史记录
        $deleteIds = [];
        foreach($histories as $history){
            $deleteIds[] = $history->id;
        }

        $result = BrowsingHistoryModel::where('id', 'in', $deleteIds)->delete();
        if($result){
            $this->success('删除成功', ['deleted_count' => $result]);
        }else{
            $this->error('删除失败');
        }
    }

    //清空浏览历史
    public function del_all_history(){
        // 验证用户登录
        $user = $this->auth->getUser();
        if(!isset($user['id'])||!$user['id']){
            $this->error('当前登录用户不存在');
        }

        // 删除该用户的所有浏览历史记录
        $result = BrowsingHistoryModel::where('user_id', $user['id'])->delete();
        if($result !== false){
            $this->success('清空成功', ['deleted_count' => $result]);
        }else{
            $this->error('清空失败');
        }
    }

    protected function formatScore($score)
    {
        if ($score === null || $score === '') {
            return $score;
        }
        if (is_numeric($score)) {
            $score = (float)$score;
            
            // 最简单最傻瓜式的判断
            // 小于等于0 -> 0
            if ($score <= 0) {
                return '0.0';
            }
            
            // 大于等于10 -> 5
            if ($score >= 10) {
                return '5.0';
            }
            
            // 其他情况：向下取整得到整数部分
            $intPart = (int)floor($score);
            
            // 判断是否为整数（分数的小数部分是否接近0）
            $isInteger = abs($score - $intPart) < 0.001;

            $formattedScore = $intPart * 0.5;
//            if ($isInteger) {
//                // 整数：n * 0.5
//                // 1 -> 0.5, 2 -> 1.0, 3 -> 1.5, 4 -> 2.0, ...
//                $formattedScore = $intPart * 0.5;
//            } else {
//                // 小数：(n+1) * 0.5
//                // 0.1-0.9 -> 0.5, 1.1-1.9 -> 1.0, 2.1-2.9 -> 1.5, ...
//                $formattedScore = ($intPart + 1) * 0.5;
//            }
            
            return number_format($formattedScore, 1, '.', '');
        }
        return $score;
    }
}
